package com.dem.android.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;

import com.dem.android.R;
import com.dem.android.adapter.DemRuAdapter;
import com.dem.android.db.DemQuery;
import com.dem.android.db.DemsColumns;
import com.dem.android.model.Dems;
import com.dem.android.model.DemsType;
import com.dem.android.service.UpdateService;
import com.dem.android.util.Config;
import com.dem.android.util.DetachableResultReceiver;
import com.dem.android.util.DetachableResultReceiver.Receiver;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class ListDemsRuActivity extends GAActivity implements OnItemClickListener, Receiver, LoaderManager.LoaderCallbacks<Cursor>, OnItemSelectedListener {

	private DetachableResultReceiver receiver;
	private DemRuAdapter adapter;
	private ListView listView;
	public static final String ADS_ID = "a14f16a9d7ca4ec";
	private ImageView imagePrev;
	private ImageView imageNext;
	private static int page = 1;
	private int pageNumaber = 200;
	private ProgressDialog progress;
	private String[] numbers;
	private Spinner spinner;
	private DemsType dType;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		numbers = new String[pageNumaber];
		for (int i = 1; i <= pageNumaber; i++) {
			numbers[i - 1] = String.valueOf(i);
		}

		switch (getIntent().getIntExtra(Config.DEM_TYPE, 0)) {
		case Config.DEM_RU:
			dType = DemsType.RU;
			break;
		case Config.DEM_US:
			dType = DemsType.US;
			break;

		default:
			break;
		}

		spinner = (Spinner) findViewById(R.id.spinner);
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, numbers);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(dataAdapter);
		spinner.setOnItemSelectedListener(this);

		imagePrev = (ImageView) findViewById(R.id.previous);
		imagePrev.setEnabled(false);
		imageNext = (ImageView) findViewById(R.id.next);

		listView = (ListView) findViewById(R.id.list);
		listView.setOnItemClickListener(this);

		// updateList(page, dType.getType());

		Bundle bundle = new Bundle();
		bundle.putString(Config.DEM_TYPE, dType.getName());
		getSupportLoaderManager().initLoader(DemQuery._TOKEN, bundle, this);

		// updatePageNumber();

		LinearLayout layout = (LinearLayout) findViewById(R.id.ads);
		AdView adView = new AdView(this, AdSize.BANNER, ADS_ID);
		layout.addView(adView);
		AdRequest request = new AdRequest();
//		request.setTesting(true);
		adView.loadAd(request);

	}

	private void updateList(int page, int type) {

		progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, true);

		Bundle bundle = new Bundle();
		bundle.putString(Config.DEM_TYPE, dType.getName());
		getSupportLoaderManager().restartLoader(DemQuery._TOKEN, bundle, this);

		Intent updateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateService.class);
		updateIntent.putExtra(UpdateService.EXTRA_STATUS_RECEIVER, receiver);
		updateIntent.putExtra(Config.DEM_TYPE, type);
		updateIntent.putExtra(Config.PAGE, page);
		startService(updateIntent);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		page = 1;
	}

	// private void updatePageNumber() {
	// pageNumaber.setText(getString(R.string.page).concat(" ").concat(String.valueOf(page)));
	// }

	public void prev(View view) {
		if (page > 1) {
			spinner.setSelection(page -= 2);
			if (page == 0)
				imagePrev.setEnabled(false);
		}
	}

	public void next(View view) {
		// updateList(page += 1, dType.getType());
		// updatePageNumber();
		// spinner.setSelection(page += 1);
		spinner.setSelection(page);
//		imagePrev.setEnabled(true);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

		ImageView imView = (ImageView) view.findViewById(R.id.image);
		String thumbnail = (String) imView.getTag();

		try {
			Intent intent = new Intent(ListDemsRuActivity.this, DetailDemRuActivity.class);
			intent.putExtra(Config.DEM_RU_DETAIL, thumbnail);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case DemQuery._TOKEN:
			return new CursorLoader(ListDemsRuActivity.this, Dems.CONTENT_URI, DemQuery.PROJECTION, DemsColumns.TYPE.getName() + " = '"
					+ bundle.getString(Config.DEM_TYPE) + "' and " + DemsColumns.PAGE.getName() + " = '" + page + "'", null, Dems.DEFAULT_SORT);
		default:
			return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case DemQuery._TOKEN:
			if (cursor != null && cursor.getCount() != 0 && progress != null) {
				progress.dismiss();
			}
			startManagingCursor(cursor);
			if (adapter == null) {
				adapter = new DemRuAdapter(ListDemsRuActivity.this, cursor);
				listView.setAdapter(adapter);
			} else {
				adapter.changeCursor(cursor);
				adapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		adapter.swapCursor(null);

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateService.STATUS_RUNNING:
			break;
		case UpdateService.STATUS_ERROR:
			break;
		case UpdateService.STATUS_FINISHED:
			Bundle bundle = new Bundle();
			bundle.putBoolean(Config.HIDE_PROGRESS, true);
			bundle.putString(Config.DEM_TYPE, dType.getName());
			getSupportLoaderManager().destroyLoader(DemQuery._TOKEN);
			getSupportLoaderManager().initLoader(DemQuery._TOKEN, bundle, this);
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
		// Log.v("position", "" + (position + 1));
		page = position + 1;
		if (page > 1)
			imagePrev.setEnabled(true);
		else if (page == 1)
			imagePrev.setEnabled(false);
		
		if (page < numbers.length)
			imageNext.setEnabled(true);
		else if (page == numbers.length)
			imageNext.setEnabled(false);
		updateList(page, dType.getType());

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}
}